//
//  NewsViewController.m
//  Finance
//
//  Created by cheng xiang on 13-4-2.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsViewCell.h"
#import "NewsDetailView.h"
#import "AppDelegate.h"

@interface NewsViewController ()

@end

@implementation NewsViewController
@synthesize tableView = _tableView,loadFooterView = _loadFooterView;
@synthesize array = _array,reloading = _reloading,currentOffsetPoint = _currentOffsetPoint;
@synthesize refreshTableView = _refreshTableView,type = _type,pageIndex = _pageIndex;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.pageIndex = 0;
    self.type = ServerTypeRefresh;
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-44) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    [self.view addSubview:_tableView];
    
    if (_refreshTableView == nil) {
        EGORefreshTableHeaderView *refreshView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
        refreshView.delegate = self;
        [self.tableView addSubview:refreshView];
        _refreshTableView = refreshView;
    }
        
    _array = [[NSMutableArray alloc] init];
    
    if (_loadFooterView == nil) {
		
		_loadFooterView = [[LoadMoreFooterView alloc] initWithFrame: CGRectZero];
		[self.tableView addSubview:_loadFooterView];
	}
    
    [self packageRequest];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(goReturn)];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    UIColor* bk = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"beij.png"]];
    [self.tableView setBackgroundColor:bk];
}

- (void)viewDidAppear:(BOOL)animated
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *aController = (UITabBarController *)delegate.window.rootViewController;
    [delegate hideTabBar:aController];
}

- (void)viewDidDisappear:(BOOL)animated
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *aController = (UITabBarController *)delegate.window.rootViewController;
    [delegate showTabBar:aController];
}

- (void)goReturn
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)packageRequest
{
    //组请求报文
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W113"];
    if (self.type == ServerTypeRefresh) {
        self.pageIndex = 0;
    }
    NSDictionary *body = [self PackageBody:self.pageIndex];
    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
    
    //发送报文
    [self getTableData: requestJson];
}

//每次组报文需要实现类似组body的方法
- (NSDictionary *)PackageBody:(int)index
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"pageIndex"] = [NSString stringWithFormat:@"%d",index];
    dic[@"pageSize"] = AMOUNT_MIN;
    return dic;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"contentSize"])
    {
        if ([_array count] >= AMOUNT_MIN.intValue) {
            _loadFooterView.frame = CGRectMake(0.0f, self.tableView.contentSize.height > self.tableView.bounds.size.height ? self.tableView.contentSize.height : self.tableView.bounds.size.height, 320, 250);
        }else{
            _loadFooterView.frame = CGRectZero;
        }
    }
}

- (void)getTableData:(NSData *)data
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"QueryNewsBasic"] toObject:self callBack:@selector(requestCallBack:) withBody:data];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([_array count] >= AMOUNT_MIN.intValue) {
        _loadFooterView.delegate = self;
        _loadFooterView.arrowImage.hidden = NO;
    }else{
        _loadFooterView.delegate = nil;
        _loadFooterView.arrowImage.hidden = YES;
    }
    return [_array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = [NSString stringWithFormat:@"%d",indexPath.row];
    NewsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NewsViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        [cell setAccessoryType:UITableViewCellAccessoryNone];
        cell.selectionStyle= UITableViewCellSelectionStyleNone;
        
        UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 78, cell.frame.size.width, 2)];
        lineImageView.image = [UIImage imageNamed:@"line-gray.png"];
        [cell.contentView addSubview:lineImageView];
        
        
        
        UIImageView *rightview = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.size.width-30, 30, 10, 15)];
        rightview.image = [UIImage imageNamed:@"形状 1.png"];
        [cell.contentView addSubview:rightview];
        
    }
    [cell drawCell:[_array objectAtIndex:indexPath.row]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [_array objectAtIndex:[indexPath row]];
    NSString *newId = [dic objectForKey:@"newsId"];
    NewsDetailView *detailView = [[NewsDetailView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setDuration:0.3];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromRight;
    animation.fillMode = kCAFillModeForwards;
    [detailView.layer addAnimation:animation forKey:@"pageAnimation"];
    [detailView getDataForId:newId];
    [self.view.window addSubview:detailView];
    
}

- (void)requestCallBack:(NSDictionary *)dic
{
    NSObject *body = dic[@"body"];
    NSLog(@"%@",[body class]);
    if([body isKindOfClass:[NSDictionary class]] && [(NSDictionary *)body objectForKey:@"news"] != nil)
    {
        switch (_type) {
            case ServerTypeRefresh:
                self.array = [(NSDictionary *)body objectForKey:@"news"];
                break;
            case ServerTypeLoadMore:
                [self.array addObjectsFromArray:[(NSDictionary *)body objectForKey:@"news"]];
                break;
            default:
                break;
        }
        
    }
    
    [self doneLoadingTableViewData];
    
    [self.tableView reloadData];
}

- (void)reloadTableViewDataSource{
    _reloading = YES;
    [self packageRequest];
    //[NSThread detachNewThreadSelector:@selector(doInBackground) toTarget:self withObject:nil];
}

- (void)doneLoadingTableViewData{
    NSLog(@"doneLoadingTableViewData");
    
    _reloading = NO;
    switch (_type) {
        case ServerTypeRefresh:
            [_refreshTableView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
            break;
        case ServerTypeLoadMore:
            [_loadFooterView loadMoreScrollViewDataSourceDidFinishedLoading:self.tableView];
            break;
        default:
            break;
    }

}

-(void)viewDidUnload
{
    [_tableView removeObserver:self forKeyPath:@"contentSize"];
    _refreshTableView = nil;
    _loadFooterView = nil;
    [super viewDidUnload];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{
    _type = ServerTypeRefresh;
    [self reloadTableViewDataSource];
}

-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{
    return _reloading;
}

-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
    return [NSDate date];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    self.currentOffsetPoint = scrollView.contentOffset;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_refreshTableView egoRefreshScrollViewDidScroll:scrollView];
    if (_loadFooterView.delegate != nil) {
        [_loadFooterView loadMoreScrollViewDidScroll:scrollView];
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_refreshTableView egoRefreshScrollViewDidEndDragging:scrollView];
    if (_loadFooterView.delegate != nil) {
        [_loadFooterView loadMoreScrollViewDidEndDragging:scrollView];
    }
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)loadMoreTableFooterDidTriggerRefresh:(LoadMoreFooterView *)view{
	_pageIndex++;
    _type = ServerTypeLoadMore;
	[self reloadTableViewDataSource];
    
    
	//[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:4.0];
	
}

- (BOOL)loadMoreTableFooterDataSourceIsLoading:(LoadMoreFooterView *)view{
	
	return _reloading; // should return if data source model is reloading
	
}

@end
